/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package csvconvertor;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

/**
 *
 * @author sajin
 */
public class CSVConvertor {
	public CSVConvertor( HashMap<String,String> headerMap,
		HashMap<String,Integer> locMap,
		HashMap<String,Boolean> dropFields,
		String csvInFile, String csvOutFile ) {
		// Read the csvInFile convert it into
		// the CSV Format defined by headerMap.
		// Write it to the CSV outFile.

		this.headerMap = headerMap;
		this.locMap = locMap;
		this.dropFields = dropFields;
		this.csvInFile = csvInFile;
		this.csvOutFile = csvOutFile;

	}

	public void Convert() {
		CSVReader csvRd;
		CSVWriter csvWr;
		String[] inHeaders;
		String[] outHeaders;
		String[] inFields;
		String[] outFields;

		try{
			csvRd = new CSVReader(csvInFile);
			csvWr = new CSVWriter(csvOutFile);

			inHeaders = csvRd.getHeaderFields();

			int outHeaderLength = 0;
			for ( String hdField : inHeaders ) {
				if ( !dropFields.get(hdField)) {
					outHeaderLength++;
				}
			}

			outHeaders = new String[outHeaderLength];

			int loc = 0 ;

			for ( String hdField : inHeaders ) {
				if(!dropFields.get(hdField))
					outHeaders[loc++] = headerMap.get(hdField);
			}


			csvWr.writeHeaderFields(outHeaders);

			while ( ( inFields = csvRd.getFields() ) != null ) {
				outFields = new String[outHeaderLength];
				loc = 0;

				for ( String hdField: inHeaders ) {
					if ( !dropFields.get(hdField)) {
						outFields[locMap.get(hdField)] = inFields[loc];
					}
					loc++;
				}
				csvWr.writeFields(outFields);
			}

		} catch (FileNotFoundException fExp) {
			System.err.println("Error Occured:");
		} catch (IOException iexp) {
			System.out.println("Error Occured:");
		}
	}

	protected HashMap<String,String> headerMap;
	protected HashMap<String,Integer> locMap;
	protected HashMap<String,Boolean> dropFields;
	protected String csvInFile;
	protected String csvOutFile;

}
